
''' <summary>
''' Controller used to call the FileManager web service.
''' </summary>
''' <remarks>
''' All methods are meant to be called Async. and provide events to handle 
''' application flow. 
''' ITLackey 10.29.07
''' 
''' Updated to use IWebCF File Manager ITLackey 02.17.08
''' </remarks>
Public Class FileController

    Private _factory As ProxyFactory

    Public ReadOnly Property Factory() As ProxyFactory
        Get
            If _factory Is Nothing Then

                _factory = New ProxyFactory _
                    (My.Forms.LoginForm.HttpsRadioButton.Checked, _
                     My.Forms.LoginForm.AddressTextBox.Text)
            End If

            Return _factory
        End Get
    End Property

#Region "Events"

    Friend Event FolderCreated As EventHandler(Of NewFolderEventArgs)

    Friend Event FilesDeleting As EventHandler(Of DeleteFilesEventArgs)

    Friend Event FilesDeleted As EventHandler(Of DeleteFilesEventArgs)

    Friend Event FileInfoReceived As EventHandler(Of GetFileInfoEventArgs)

    Friend Event FileDownloaded As EventHandler(Of DownloadFileEventArgs)

    Friend Event FileDownloading As EventHandler(Of DownloadFileEventArgs)

    Friend Event FileUploaded As EventHandler(Of FileTransferEventArgs)

    Friend Event FileUploading As EventHandler(Of FileTransferEventArgs)

    Friend Event FolderListReceived As EventHandler(Of GetFoldersEventArgs)

    Friend Event FileListReceived As EventHandler(Of GetFilesEventArgs)

#End Region

    Friend Sub AddNewFolderAsync(ByVal args As IWebCFExplorer.NewFolderEventArgs)

        Try



            Using fileManager As IWebCF.WebFileManagerClient = _
                 Factory.GetProxy(Of IWebCF.WebFileManagerClient) _
                (CoreEndPoints.WebFileManager)


                fileManager.AddFolder(args.Header, args.NewFolderName, args.FolderId)

            End Using

            args.Status = args.NewFolderName & " was created."


        Catch ex As Exception

            args.HasError = True

            args.Status = ex.Message

        End Try

        RaiseEvent FolderCreated(Me, args)


    End Sub

    'Friend Sub DeleteFilesAsync(ByVal args As DeleteFilesEventArgs)

    '    Try

    '        RaiseEvent FilesDeleting(Me, args)

    '        Using fileManager As IWebCF.WebFileManagerClient = _
    '             Factory.GetProxy(Of IWebCF.WebFileManagerClient) _
    '            (CoreEndPoints.WebFileManager)

    '            args.Status = String.Format("{0} files deleted.", _
    '                fileManager.DeleteFiles(args.Header, New List(Of Integer)(args.FileIds)))

    '        End Using

    '        args.HasError = False

    '    Catch ex As Exception

    '        args.HasError = True

    '        args.Status = ex.Message

    '    End Try

    '    RaiseEvent FilesDeleted(Me, args)

    'End Sub


    Friend Function DownloadFile(ByVal args As DownloadFileEventArgs) As DownloadFileEventArgs

        args.Status = String.Format("Downloading {0}", args.FileName)

        RaiseEvent FileDownloading(Me, args)

        Try


            Dim fileContent As Byte()


            Using service As IWebCF.WebFileTransferManagerClient = _
                 Factory.GetProxy(Of IWebCF.WebFileTransferManagerClient) _
                (CoreEndPoints.WebFileTransferManager)

                fileContent = service.DownloadFile(args.Header, args.FileId)

                If fileContent IsNot Nothing Then
                    IO.Directory.CreateDirectory(IO.Path.GetDirectoryName(args.FileName))

                    IO.File.WriteAllBytes(args.FileName, fileContent)

                End If

            End Using

            args.Status = String.Format("File saved to {0}", args.FileName)

            args.HasError = False

        Catch ex As Exception

            args.Status = ex.Message

            args.HasError = True

        End Try

        RaiseEvent FileDownloaded(Me, args)

        Return args

    End Function

    Friend Sub GetFileListAsync(ByVal args As GetFilesEventArgs)

        Try

            Using fileManager As IWebCF.WebFileManagerClient = _
              Factory.GetProxy(Of IWebCF.WebFileManagerClient)(CoreEndPoints.WebFileManager)

                args.Files = fileManager.GetFilesByFolder(args.Header, args.FolderId)

                args.Status = String.Format("{0} Files. {1}", args.Files.Count, _
                    fileManager.GetPortalSpaceUsed(args.Header, True))

            End Using

            args.HasError = False

        Catch ex As Exception

            args.HasError = True

            args.Status = ex.Message

            args.Files = New List(Of IWebCF.FileInfoDataContract)


        End Try

        RaiseEvent FileListReceived(Me, args)


    End Sub

    Friend Sub GetFolderListAsync(ByVal args As GetFoldersEventArgs)

        Try


            Using fileManager As IWebCF.WebFileManagerClient = _
                 Factory.GetProxy(Of IWebCF.WebFileManagerClient) _
                (CoreEndPoints.WebFileManager)

                args.Folders = fileManager.GetFoldersByParent(args.Header, args.FolderId)

                args.Status = String.Format("{0} subfolders. {1}", args.Folders.Count, _
                    fileManager.GetPortalSpaceUsed(args.Header, True))

                args.HasError = False

            End Using

        Catch ex As Exception

            args.HasError = True

            args.Status = ex.Message

            args.Folders = New List(Of IWebCF.FolderInfoDataContract)


        End Try

        RaiseEvent FolderListReceived(Me, args)


    End Sub

    Friend Sub GetFileInfoAsync(ByVal args As GetFileInfoEventArgs)

        Try

            Using fileManager As IWebCF.WebFileManagerClient = _
                  Factory.GetProxy(Of IWebCF.WebFileManagerClient) _
                 (CoreEndPoints.WebFileManager)

                Dim info As IWebCF.FileInfoDataContract = fileManager.GetFileById(args.Header, args.FileId)

                args.File = info

            End Using

        Catch ex As Exception

            args.File = New IWebCF.FileInfoDataContract
            args.HasError = True
            args.Status = ex.Message

        End Try

        RaiseEvent FileInfoReceived(Me, args)

    End Sub

    Friend Function UploadFile(ByVal args As FileTransferEventArgs) As FileTransferEventArgs


        args.Status = String.Format("Uploading {0}", args.FileName)

        RaiseEvent FileUploading(Me, args)

        Try


            Dim fileToUpload As System.IO.FileStream = New IO.FileStream(args.FileName, IO.FileMode.Open, IO.FileAccess.Read)


            Using fileManager As IWebCF.WebFileManagerClient = _
                 Factory.GetProxy(Of IWebCF.WebFileManagerClient) _
                (CoreEndPoints.WebFileManager)


                Dim maxRequestLength As Long = fileManager.GetMaxRequestLength(args.Header)

                If (New IO.FileInfo(args.FileName).Length / 1024) > maxRequestLength Then

                    args.Status = "File too large maximum request length is: " & _
                       (maxRequestLength / 1024).ToString("0.00") & "MB"


                    args.HasError = True

                Else


                    Dim fileContent As Byte() = IO.File.ReadAllBytes(args.FileName)


                    Using uploader As IWebCF.WebFileTransferManagerClient = _
                        Factory.GetProxy(Of IWebCF.WebFileTransferManagerClient) _
                        (CoreEndPoints.WebFileTransferManager)


                        uploader.UploadFile(args.Header, fileContent, args.FileName, args.FolderId)

                    End Using

                    args.HasError = False

                    args.Status = String.Format("Uploaded {0}", args.FileName)

                End If
            End Using

        Catch webEx As Net.WebException

            Select Case webEx.Status
                Case Net.WebExceptionStatus.MessageLengthLimitExceeded, _
                    Net.WebExceptionStatus.ProtocolError

                    args.Status = String.Format _
                        ("File {0} may have exceeded the maxium request length.", args.FileName)

                Case Net.WebExceptionStatus.SecureChannelFailure
                    args.Status = "Could not establish SSL connection."

                Case Net.WebExceptionStatus.Timeout
                    args.Status = String.Format("The request for file {0} has timed out.", args.FileName)

                Case Net.WebExceptionStatus.ConnectionClosed
                    args.Status = "Connection closed."

                Case Else
                    args.Status = webEx.Status.ToString


            End Select

            args.HasError = True


            My.Application.Log.WriteException(webEx, TraceEventType.Error, _
                "During uploading of " & args.FileName)


        Catch ex As Exception

            args.HasError = True

            args.Status = ex.Message


        End Try



        RaiseEvent FileUploaded(Me, args)

        Return args

    End Function



    Private Sub FileController_FilesDeleted(ByVal sender As Object, ByVal e As DeleteFilesEventArgs) Handles Me.FilesDeleted

    End Sub
End Class
